<template>
  <div class="box">
    <el-container>
      <div class="mostTop"></div>
      <el-header class="clearfix">
        <p class="addCourseTitle">新增学生</p>
        <p class="return" @click="back()">< 返回</p>
      </el-header>
      <el-main>
        <p class="courseDetails">基本信息</p>
        <div class="inputTitle clearfix">
          <div class="left">
            <p>名字</p>
            <el-input v-model="name" placeholder="名字"></el-input>
            <p>性别</p>
              <el-select v-model="sex" placeholder="选择性别" class="selectTeacher" >
              <el-option v-for="item1 in option1" :key="item1.value" :label="item1.label" :value="item1.value">
              </el-option>
            </el-select>
            <p>家庭地址</p>
            <el-input v-model="address" placeholder="家庭地址"></el-input>
            <p>父母名字</p>
            <el-input v-model="nameparents" placeholder="父母名字"></el-input>
            <p>父母联系电话</p>
            <el-input v-model="parentsphone" placeholder="父母联系电话"></el-input>
            <p>学生头像</p>
            <div slot="tip" class="el-upload__tip">
              单文件大小请在2M以内,仅支持JPG格式
            </div>
            <div id="upload">
              <el-upload class="avatar-uploader" action="/image" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="uploadFile" >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
          <div class="right">
             <p>学号</p>
            <el-input v-model="studentId" placeholder="学号"></el-input>
            <p>电子邮件</p>
            <el-input v-model="mail" placeholder="电子邮件"></el-input>
            <p>班级</p>
            <el-select v-model="classname" placeholder="选择班级" class="selectTeacher" >
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <p>入学时间</p>
            <div class="block">
              <el-date-picker v-model="admissiontime" type="date" placeholder="入学日期不可以大于今天" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" class="date"
              >
              </el-date-picker>
            </div>
            <p>出生日期</p>
            <div class="block">
              <el-date-picker v-model="datebirth" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" class="date" >
              </el-date-picker>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <div id="footBox">
      <div id="footer">
        <el-button type="info" @click="cancle" :plain="true">取消</el-button>
        <el-button type="success" @click="addStudent" :plain="true">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageUrl: "",
      textarea: "",
      //班级
      options: [
        {
          value: "1",
          label: "高二(1)班",
        },
        {
          value: "2",
          label: "高二(2)班",
        },
        {
          value: "3",
          label: "高二(3)班",
        },
      ],
      //性别
       option1: [
        {
          value: "1",
          label: "男",
        },
        {
          value: "2",
          label: "女",
        },
      ],
     name:'',
     sex:'',
     address:'',
     nameparents:'',
     parentsphone:'',
     id:'',
     mail:'',
     classname:'',
     admissiontime:'',
     datebirth:'',
     studentId:'',
    };
  },
  methods: {
    //取消
    cancle() {
        this.$confirm('检测到有未保存的内容，确认是否离开？', '确认信息', {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存',
            cancelButtonText: '离开'
        })
            .then(() => {
                this.baocun();
            })
            .catch(action => {
                this.$message({
                    type: 'info',
                    message: action === 'cancel'
                        ? '放弃保存并离开页面'
                        : '停留在当前页面'
                });
                this.$router.push("/administrator");
            });
    },
    
    handlePreview(file) {
    },
    //返回
    back() {
      this.$router.go(-1);
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //判断年龄  加入时间要大于出生日期
    judgeTime(){
    var time2 = new Date(this.datebirth).getTime();
     var time3 =  new Date(this.admissiontime).getTime();
      //判断
      if(time2<time3){
         return true;
      }else{
        this.$message.error('出生日期或加入日期填写错误！');
        return false;
      }
    },
    //判断加入时间
    judgeJoin(){
      //获取当前时间
       var date = Date.now();
      var time = new Date(date).getTime();
      var time1= new Date(this.admissiontime).getTime()
      //判断
      if(time1<time){
         return true;
      }else{
        this.$message.error('入学日期不能大于今天,填写错误！');
        return false;
      }
    },

    //手机号验证
    phoneyz() {
        var reg = /^1[3-9]\d{9}$/;
        if (!reg.test(this.parentsphone)) {
            this.$message.error('手机格式不正确，请重新输入！');
            return false;
        } else {
            return true;
        }
    },
    //邮箱验证
    emailyz() {
        //邮箱正则
        var emreg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!emreg.test(this.mail)) {
            this.$message.error('邮箱格式不正确，请重新输入！');
            return false;
        } else {
            return true;
        }
    },

    //添加学生
    addStudent(){
      var n=this.options[this.classname-1].label
      // console.log(this.options[this.classname-1])
      if(this.sex=='女'){
        this.sex=0
      }else if(this.sex=='男') {
        this.sex=1
      }
      if(this.nameparents==''||this.studentId==''||this.parentsphone==''||this.name==''||this.classname==''||this.mail==''){
          this.$message.error('请填写完整信息');
      }else{
          if (this.phoneyz()) {//判断电话号码
              if (this.emailyz()) {//判断邮箱
                if( this.judgeTime()){
                  if( this.judgeJoin()){
                    this.$axios({
                        url:"/student/insert",
                        method:'post',
                        data:{
                                "address":  this.address,
                                "admissionDate": this.admissiontime,
                                "birthday": this.datebirth,
                                "className": n,
                                "classid": this.classname,
                                "email": this.mail,
                                "id": null,
                                "image": this.imageUrl,
                                "name":this.name,
                                "parentName":this.nameparents,
                                "parentPhone":this.parentsphone,
                                "sex":this.sex,
                                "studentId":this.studentId
                        }
                    }).then(res=>{
                      if(res.data.code == 50008){
                        this.open3()
                      }else if(res.data.code == 50003){
                         this.$router.push("/noResponse");
                      }
                      else{
                        this.open2()
                        this.$router.push("/Student");
                      }
                        
                    }).catch(error=>{
                        this.open4()
                        console.log(error,2);
                    })
                }
              }
          }
            }
        }
      
    },
     //成功
    open2(){
      this.$message({
            message: '恭喜你，操作成功',
            type: 'success'
      });
    },
    //警告
     open3() {
        this.$message({
          message: '警告哦，该学号已存在',
          type: 'warning'
        });
      },
     //失败
    open4() {
        this.$message.error('操作失败');
    },
  },

};
</script>
<style lang="less" scoped>
.clearfix:after {
  content: "";
  clear: both;
  display: block;
}
.box {
  background: #f2f2f6;
}
.el-header {
  background-color: #fff;
  margin-top: 10px;
  line-height: 30px;
  .addCourseTitle {
    color: #333;
    float: left;
    font-size: 18px;
  }
  .return {
    color: #333;
    float: right;
    font-size: 18px;
    cursor: pointer;
  }
  .return:hover {
    color: #8cc5ff;
  }
}
.el-main {
  margin-top: 10px;
  background-color: #fff;
  color: #333;
  .courseDetails {
    font-weight: bold;
  }
  .inputTitle {
    width: 100%;
    .left {
      float: left;
      width: 47%;
      .select {
        width: 100%;
        .selectChildren {
          width: 50%;
        }
      }
      #upload {
        width: 178px;
        height: 178px;
        border: 1px dashed #6b6767;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload {
        border: 1px dashed #cfa1a1;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #587397;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
    .right {
      margin-left: 6%;
      float: left;
      width: 47%;
      .date {
        width: 100%;
      }
      .selectTeacher {
        width: 100%;
      }
    }
  }
}
#footBox {
  width: 100%;
  height: 350px;
  background: white;
}
#footer {
  margin-left: 43%;
  height: 200px;
  .el-button {
    float: left;
    margin-top: 100px;
  }
}
body > .el-container {
  margin-bottom: 40px;
}
</style>